﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using NHibernate.Mapping;
using com.pro2e.console.service.auth.vo;
using com.pro2e.console.service.auth.dao;
using System.Collections.Generic;
using System.Collections;
using com.pro2e.web.config.init;
using Iesi.Collections.Generic;
using com.pro2e.console.service.core;
using com.pro2e.console.core.util;
using NHibernate.Criterion;

/// <summary>
/// AuthService 的摘要描述
/// </summary>
/// 

namespace com.pro2e.console.service.auth
{
    public class AuthService : ServiceImpl
    {
        log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        LoginRoleDao loginRoleDao = new LoginRoleDao();
        LoginUserDao loginUserDao = new LoginUserDao();
        MenuFuncDao menuFuncDao = new MenuFuncDao();

        public AuthService()
        {

        }

        public IList<LoginRole> GetAllRoles()
        {

            return (loginRoleDao.DaoGetAllVO<LoginRole>());
        }

        public LoginRole GetLoginRole(int id)
        {
            return (loginRoleDao.DaoGetVOById<LoginRole>(id));
        }

        public void DeleteRole(LoginRole loginRole)
        {
            if (loginRole.BelongUsers != null && loginRole.BelongUsers.Count > 0)
            {
                throw new Exception("權限下還有使用者");
            }

            loginRoleDao.DaoDelete(GetLoginRole(loginRole.RoleId));
        }

        public void UpdateRole(LoginRole loginRole)
        {
            loginRoleDao.DaoUpdate(loginRole);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IList<LoginUser> GetAllUsers()
        {
            return (loginUserDao.DaoGetByWhere<LoginUser>("1=1 ORDER BY ArrivedDate"));
        }

        public void DeleteUser(LoginUser loginUser)
        {

            log.Debug("delete userId=" + loginUser.UserId);

            LoginUser newUser = loginUserDao.DaoGetVOById<LoginUser>(loginUser.UserId);
            loginUserDao.DaoDelete(newUser);

        }

        public void UpdateUser(LoginUser loginUser)
        {
            loginUserDao.DaoUpdate(loginUser);
        }

        public LoginUser LoadLoginUser(string userId)
        {
            return (loginUserDao.DaoGetVOById<LoginUser>(userId));
        }

        public void AddLoginUser(LoginUser newUser)
        {
            loginUserDao.DaoInsert(newUser);
        }

        public void AddRole(LoginRole loginRole)
        {
            loginRoleDao.DaoInsert(loginRole);
        }


        /// <summary>
        ///  登入
        /// </summary>
        /// <param name="id">帳號</param>
        /// <param name="pw">密碼</param>
        /// <returns>登入成功則傳回LoginUser失敗則為null</returns>
        public LoginUser Login(string id, string pw)
        {
            LoginUser loginUser = LoadLoginUser(id);
            if (loginUser != null && loginUser.Password.Equals(pw))
            {
                return loginUser;
            }
            else
            {
                return null;
            }
        }


        //internal bool PathHasAuth(LoginUser loginUser, Uri uri)
        public bool PathHasAuth(LoginUser loginUser, Uri uri)
        {
            string path = uri.ToString();

            IList<LoginRole> loginRoleList = loginUser.BelongRoles;

            HashSet<string> pathRightSet = new HashSet<string>();

            foreach (LoginRole role in loginRoleList)
            {
                IList<MenuFunc> menuFuncList = role.MenuFuncs;

                foreach (MenuFunc menuFunc in menuFuncList)
                {
                    pathRightSet.Add(menuFunc.MainPath);

                    if (menuFunc.FuncionPaths != null && menuFunc.FuncionPaths.Count > 0)
                    {
                        foreach (FunctionPath fpth in menuFunc.FuncionPaths)
                        {
                            if (!string.IsNullOrEmpty(fpth.Path))
                            {
                                pathRightSet.Add(fpth.Path);
                            }
                        }
                    }
                }
            }

            pathRightSet.Add("admin/index.aspx");
            if (pathRightSet.Count > 0)
            {
                foreach (string rightPath in pathRightSet.ToArray<string>())
                {
                    if (path.IndexOf(rightPath) != -1)
                    {
                        return true;
                    }
                }
            }

            return false;

        }

        /// <summary>
        /// 取出為第一層的MenuFunc
        /// </summary>
        /// <returns></returns>
        public IList<MenuFunc> GetTopMenuFunc()
        {
            return (menuFuncDao.GetTopMenuFuncList());

        }
        /// <summary>
        /// 取出不為第一層的MenuFunc
        /// </summary>
        /// <returns></returns>
        public IList<MenuFunc> GetNotTopMenuFunc()
        {
            return (menuFuncDao.GetNotTopMenuFunc());
        }

        /// <summary>
        /// 取出清單by parentId
        /// </summary>
        /// <param name="p">parentId</param>
        /// <returns></returns>
        public IList<MenuFunc> GetMenuFuncByParentId(int p)
        {
            return (menuFuncDao.GetMenuFuncByParentId(p));
        }


        public LoginRole GetTmpLoginRole(int p)
        {
            return (loginRoleDao.DaoGetTmpVOById<LoginRole>(p));
        }


        /// <summary>
        /// 取得屬取這個User的權限的功能清單
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public IList<MenuFunc> GetTopMenuFunc(LoginUser user, IList<MenuFunc> allMenu, Dictionary<int, LoginRole> roleDic)
        {
            IList<MenuFunc> authMenuList = new List<MenuFunc>();

            foreach (MenuFunc menu in allMenu)
            {
                if (menu.SubFuncs.Count > 0)
                {
                    int i = 1;  //判斷是否第一次執行
                    MenuFunc newFunc = new MenuFunc();

                    foreach (MenuFunc subFunc in menu.SubFuncs)
                    {
                        if (UserHasMenuRight(user, subFunc, roleDic))
                        {
                            if (i == 1)
                            {
                                newFunc = menu;
                                authMenuList.Add(newFunc);
                                newFunc.SubFuncs = new List<MenuFunc>();
                            }
                            newFunc.SubFuncs.Add(subFunc);
                            i++;
                        }
                    }
                }
            }
            return authMenuList;
        }

        /// <summary>
        /// 群組是否有此功能清單的權限
        /// </summary>
        /// <param name="role"></param>
        /// <param name="subFunc"></param>
        /// <returns></returns>
        public bool RoleHasMenuRight(LoginRole role, MenuFunc subFunc)
        {
            //if (role.MenuFuncs != null && role.MenuFuncs.Count > 0)
            //{
            //int count = DaoCountByWhere<LoginRole>("as vo where  vo.RoleId="+role.RoleId);
            //  role = DaoGetVOById<LoginRole>(role.RoleId);



            foreach (MenuFunc roleHasFunc in role.MenuFuncs)
            {
                if (roleHasFunc.Id.Equals(subFunc.Id))
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 檢查使用者是否有此單一清單的權限
        /// </summary>
        /// <param name="user"></param>
        /// <param name="subFunc"></param>
        /// <returns></returns>
        public bool UserHasMenuRight(LoginUser user, MenuFunc subFunc, Dictionary<int, LoginRole> roleDic)
        {
            if (user.BelongRoles != null && user.BelongRoles.Count > 0)
            {
                foreach (LoginRole role in user.BelongRoles)
                {
                    LoginRole cacheRole = roleDic[role.RoleId];

                    if (RoleHasMenuRight(cacheRole, subFunc))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
       

    }
}